package com.yangsy.qr_code_demo.controller;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

/**
 * @author yangSy
 * @date 2024/7/30 9:36
 */
@RestController
public class TestController {

    @RequestMapping("/api/test")
    public String test(){
        return "1111111111111";
    }

    @RequestMapping("/api/file")
    public String testFile(HttpServletRequest request, String context) throws ServletException, IOException {
        Part logo = request.getPart("logo");
        InputStream inputStream = logo.getInputStream();
        Part logoOne = request.getPart("ss");
//        System.out.println(mapFile.containsKey("logo"));
//        System.out.println(mapFile.containsKey("bg"));
        System.out.println(context);
        return "1111111111111";
    }


    @RequestMapping(value = "/logo")
    public void getQrCodeView(HttpServletRequest request,
                              @RequestParam(value = "qrCodeName",required = false) String qrCodeName,
                              @RequestParam(value = "identityId",required = false) String identityId,
                              @RequestParam(value = "promotionText",required = false) String promotionText,
                              @RequestParam(value = "type",required = false) String type, HttpServletResponse response) throws Exception {
        QrCodeGenWrapper.Builder of = QrCodeGenWrapper.of("http://www.baidu.com")
                .setH(180)
                .setW(180);

        // logo图片
        Part logo = request.getPart("logo");
        // 背景图片
        Part bg = request.getPart("bg");

        BufferedImage bgs = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("png/bgone.png"));

        // 设置logo
        if(logo != null){
            of.setLogo(logo.getInputStream());
            of.setLogoRate(7);
            of.setLogoStyle(QrCodeOptions.LogoStyle.ROUND);
        }
        // 设置背景原图
        if(bgs != null){
            of.setBgImg(bgs);
            of.setBgStyle(QrCodeOptions.BgImgStyle.FILL);
            int width = bgs.getWidth();
            int height = bgs.getHeight();
            if (width>400){
                width=400;
            }
            if (height>500){
                height=500;
            }
            of.setBgW(width);
            of.setBgH(height);
            of.setBgStartX((width-180)/2);
            of.setBgStartY(280);
        }
        BufferedImage qrcodeImage = of.asBufferedImage();


        BufferedImage opacityImage = new BufferedImage(qrcodeImage.getWidth(),qrcodeImage.getHeight(),BufferedImage.TYPE_INT_ARGB);
        float opacity = 1f; // 设置透明度，范围从 0.0 到 1.0
        Graphics2D qrcodeImageGraphics = opacityImage.createGraphics();
        // 3. 设置透明度
        qrcodeImageGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
        // 4. 绘制带透明度的图片
        qrcodeImageGraphics.drawImage(qrcodeImage, 0, 0, null);
        qrcodeImageGraphics.dispose();
        qrcodeImage=opacityImage;

        // 再填充背景图片
        if (bg!=null){

            // 首先先画背景图片
            BufferedImage backgroundImage = ImageIO.read(bg.getInputStream());


            // 2. 创建缩小后的图片
            BufferedImage resizedImage = new BufferedImage(qrcodeImage.getWidth()+50, qrcodeImage.getHeight()+50, backgroundImage.getType());
            Graphics2D g = resizedImage.createGraphics();

            // 3. 绘制缩小后的图片
            g.drawImage(backgroundImage, 0, 0, qrcodeImage.getWidth()+50, qrcodeImage.getHeight()+50, null);
            g.dispose();
            // 背景图片的宽度
            int bgWidth = backgroundImage.getWidth();
            // 二维码的宽度
            int qrWidth = qrcodeImage.getWidth();
            // 二维码距离背景图片横坐标（X）的距离，居中显示
            int distanceX = (bgWidth - qrWidth) / 2;
            // 二维码距离背景图片纵坐标（Y）的距离
            int distanceY = distanceX;
          //   基于图片backgroundImage对象打开绘图

         //   Image scaledInstance = backgroundImage.getScaledInstance(qrcodeImage.getWidth(), qrcodeImage.getHeight(), Image.SCALE_SMOOTH);

            Graphics2D rng = resizedImage.createGraphics();
            rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
            rng.drawImage(qrcodeImage, 5, 5, null);

            // 设置背景文字
            //设置字体
            Font font = new Font("宋体", Font.PLAIN, 13);
            rng.setFont(font);
            rng.setColor(Color.decode("#C91530"));
            rng.drawString("科技大学",180,50);
            // 处理绘图
            rng.dispose();
            qrcodeImage = resizedImage;
        }


        ImageIO.write(qrcodeImage,"png",response.getOutputStream());

    }
    @RequestMapping(value = "/temp")
    public void  testTem(HttpServletRequest request,
                         @RequestParam(value = "qrCodeName",required = false) String qrCodeName,
                         @RequestParam(value = "identityId",required = false) String identityId,
                         @RequestParam(value = "promotionText",required = false) String promotionText,
                         @RequestParam(value = "type",required = false) String type, HttpServletResponse response) throws Exception {
        BufferedImage templates = getTemplates();

        // 背景图片
        Part bg = request.getPart("bg");
        BufferedImage bgInput = ImageIO.read(bg.getInputStream());

        Graphics2D graphics = bgInput.createGraphics();
        float opacity = 1f;
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,opacity));
        graphics.drawImage(templates,(bgInput.getWidth()-templates.getWidth())/2,(bgInput.getHeight()-templates.getHeight())/2,null);

        // 添加顶部图案
        BufferedImage ty = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("png/ty.png"));
        graphics.drawImage(ty,(bgInput.getWidth()-ty.getWidth())/2,30,null);


        // 写身份
        Font font = new Font("宋体",Font.PLAIN,30);
        graphics.setFont(font);
        graphics.setColor(Color.BLUE);
       // TODO 多个字体需要调整，查询数据库获取identityId的身份类型

        graphics.drawString("访客",(bgInput.getWidth()-ty.getWidth())/2+30,100);

        // 写标题
        Font fontTitle = new Font("宋体",Font.PLAIN,40);
        graphics.setFont(fontTitle);
        graphics.setColor(Color.BLUE);
        graphics.drawString(qrCodeName,(bgInput.getWidth()-templates.getWidth())/2+80,230);

        // 写内容
        Font fontContext = new Font("宋体",Font.PLAIN,20);
        graphics.setFont(fontContext);
        graphics.setColor(Color.BLACK);
        // TODO 字数限制
        int x = (bgInput.getWidth()-templates.getWidth())/2+50;  // 文本起始 x 坐标
        int y = 300;  // 文本起始 y 坐标
        int lineHeight = graphics.getFontMetrics().getHeight();
        int length = promotionText.length();
        BigDecimal bigDecimal = new BigDecimal(length);
        BigDecimal divide = bigDecimal.divide(new BigDecimal("28"),BigDecimal.ROUND_UP);
        int start=0;
        int end=27;
        for (int i = 1; i <= divide.intValue(); i++) {

            if (i == divide.intValue()){
                start=end;
                end+=length-end;
                graphics.drawString(promotionText.substring(start,end),x,y);
                break;
            }
            graphics.drawString(promotionText.substring(start,end),x,y);
            y+=lineHeight;
            if (i+1 < divide.intValue()){
                start+=28;
                end+=28;
            }
        }
        graphics.dispose();


        // 生成二维码
        bgInput = QrCodeGenWrapper.of("http://www.baidu.com")
                .setH(400)
                .setW(400)
                .setBgImg(bgInput)
                .setBgW(bgInput.getWidth())
                .setBgH(bgInput.getHeight())
                .setBgStyle(QrCodeOptions.BgImgStyle.FILL)
                .setBgStartX((bgInput.getWidth() - 400) / 2)
                .setBgStartY(800)
                .asBufferedImage();

        // 响应
        ImageIO.write(bgInput,"png",response.getOutputStream());


    }

    public BufferedImage getTemplates() throws Exception {
        BufferedImage bg = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("png/bg.png"));

        BufferedImage yd = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("png/yd.png"));
        // 设置透明度
//        float opacity = 0.5f; // 设置透明度，范围从 0.0 到 1.0
//        BufferedImage newBg = new BufferedImage(bg.getWidth(),bg.getHeight(),BufferedImage.TYPE_INT_ARGB);
//        Graphics2D graphics = newBg.createGraphics();
//        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
//        graphics.drawImage(bg,bg.getWidth(),bg.getHeight(),null);
//        // 画原图
//        graphics.dispose();

        Graphics2D graphicsYd = bg.createGraphics();
        graphicsYd.drawImage(yd,80,630,null);
        graphicsYd.dispose();


        return bg;
    }

}
